package com.mhy.tvcontrol

import android.app.Activity
import android.app.UiModeManager
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import com.mhy.tv.remotecontrol.TVControl

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if(TVControl.hasOverlayPermission(this))TVControl.initTV(applicationContext)else openOverlay(this,100)
    }

    fun openOverlay(context: Context, requestCode:Int) {
        val TAG = "DeviceTypeRuntimeCheck";
        val uiModeManager =  getSystemService(UI_MODE_SERVICE) as UiModeManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
                    // "Running on a TV Device"
                } else {
            //            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
                    intent.data = Uri.parse("package:" + context.getPackageName())
//                }
                }
            if (context is Activity) {
                context.startActivityForResult(intent,requestCode)
            }else{
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                context.startActivity(intent)
            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==100){
            if (TVControl.hasOverlayPermission(this)){
                TVControl.initTV(applicationContext)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
       // TVControl.hide()
    }
}